package com.acme.hibernate.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.acme" })
public class HibernateConfig {
	@Bean
	public DataSource dataSource(){
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		ds.setUrl("jdbc:sqlserver://192.168.3.153:1433;DatabaseName=AcmeClaimsDatabase;");
		ds.setUsername("dbuser");
		ds.setPassword("dbpassword");
		return ds;
	}
	 
	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
		sf.setHibernateProperties(hibernateProperties());
		sf.setDataSource(dataSource());
		sf.setPackagesToScan(new String[] { "com.acme" });
		
		return sf;
	}
	
	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory sf){
		HibernateTransactionManager tm = new HibernateTransactionManager();
		tm.setSessionFactory(sf);
		return tm;
	}
	 
	@Bean
	public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
		return new PersistenceExceptionTranslationPostProcessor();
	}
	 
	Properties hibernateProperties() {
		Properties p = new Properties();
		p.put("hibernate.dialect", "org.hibernate.dialect.SQLServer2008Dialect");
		p.put("hibernate.show_sql", "false");
		//p.put("hibernate.connection.url", "jdbc:sqlserver://localhost\\sqlexpress:1433;DatabaseName=AcmeClaimsDatabase;integratedSecurity=true");
		p.put("hibernate.hbm2ddl.auto", "validate");
		return p;
	}
}